package com.itheima.controller;

import com.alibaba.dubbo.config.annotation.Reference;
import com.alibaba.fastjson.JSON;
import com.itheima.constant.MessageConstant;
import com.itheima.constant.RedisMessageConstant;
import com.itheima.entity.Result;
import com.itheima.pojo.Member;
import com.itheima.service.MemberService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import redis.clients.jedis.JedisPool;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletResponse;
import java.util.Date;
import java.util.Map;

/*
 * 会员登录
 * */
@RequestMapping("/member")
public class MemberController {

    @Autowired
    private JedisPool jedisPool;

    @Reference
    private MemberService memberService;

    @RequestMapping("/login")
    public Result login(HttpServletResponse response, @RequestBody Map map) {
        String telephone = (String) map.get("telephone");
        String orderDate = (String) map.get("orderDate");
        // 进行验证码的校验   因为进行验证码校验时,需要用到redis里的数据,但是要用手机号去找对应的验证码,所以第一步应该是获取map中的手机号
        String validateCode4Redis = jedisPool.getResource().get(telephone + RedisMessageConstant.SENDTYPE_LOGIN); //redis中数据
        String validateCode4Map = (String) map.get("validateCode");         //前台数据
        if (validateCode4Redis == null || !validateCode4Redis.equals(validateCode4Map)) {//如果redis中没有此数据
            return new Result(false, MessageConstant.VALIDATECODE_ERROR);
        }
        //验证码校验正确,进行数据库的查询是否存在该用户
        Member member = memberService.findByTel(telephone);
        if (member == null) {//不是会员,进行会员的注册
            member = new Member();
            member.setPhoneNumber(telephone);
            member.setRegTime(new Date());
            memberService.regist(member);
        }
        //验证码校验正确,进行加入cookie
        Cookie cookie = new Cookie("login_member_telephone",telephone);
        cookie.setPath("/");
        response.addCookie(cookie);
        //将会员信息保存到redis中
        String memberJson = JSON.toJSON(member).toString();
        jedisPool.getResource().setex(telephone,60*30,memberJson);
        return new Result(true,MessageConstant.LOGIN_SUCCESS);
    }
}
